#! /usr/bin/perl -w

# Author:   Jiahuan Li <huanlf@gmail.com>
# Licencs:  GPLv2
# Used to:  Add uming/wqy fonts dir to xorg.conf
# +         and generate fonts.scale/fonts.dir files
#           

use strict;
use File::Copy;

my $debug       = 0;    # use 1 to DEGUG
my $wqy_dir     = "/usr/share/X11/fonts/misc";
my $uming_dir   = "/usr/share/fonts/truetype/arphic";
my $xorg_conf   = "/etc/X11/xorg.conf";
my $wqy_found   = '';
my $uming_found = '';

if ( $debug ) {
    copy( $xorg_conf, "$ENV{HOME}/xorg.conf" );
    $xorg_conf = $ENV{HOME} . "/xorg.conf";
    print "Run in *DEGUG* mode, using $xorg_conf for testing ...\n\n";
}

open(FH, "<", "$xorg_conf") or die qq /Can not open "$xorg_conf" for read/;
while (<FH>) {
    $wqy_found      = 'true' if ( m!$wqy_dir! );
    $uming_found    = 'true' if ( m!$uming_dir! ); 
}

# exit if both have been configured
if ( $wqy_found && $uming_found ) {
    print "No need to configure any more, aborting ...\n" if $debug;
    exit 0;
}

die qq/Can not write to "$xorg_conf": $!/ unless -w $xorg_conf;

# now modify xorg.conf
$^I     = '.pl';    # backup postfix
@ARGV   = ($xorg_conf);

while (<>) {
    print;
    if ( m!^\s*Section\s*"Files"! ) {
        print qq/\n\tFontPath\t\t"$wqy_dir"/    unless $wqy_found;
        print qq/\n\tFontPath\t\t"$uming_dir"/  unless $uming_found;
    }
}

# generate fonts.dir/fonts.scale
if ( -d $wqy_dir && ! -e "$wqy_dir/fonts.dir" ) {   
    chdir $wqy_dir;
    if ( $debug ) {
        system( "mkfontdir" ) == 0          or warn "mkfontdir failed";
        copy( "fonts.dir", "fonts.scale" )  or warn "copy failed";
    }
    else {
        system( "mkfontdir 2>/dev/null" );
        copy( "fonts.dir", "fonts.scale" );
    }
}
if ( -d $uming_dir && ! -e "$uming_dir/fonts.dir" ) {
    chdir $uming_dir;
    if ( $debug ) {
        system( "mkfontscale" ) == 0        or warn "mkfontscale failed";
        copy( "fonts.scale", "fonts.dir" )  or warn "copy failed";
    }
    else {
        system( "mkfontscale 2>/dev/null" );
        copy( "fonts.scale", "fonts.dir" );
    }
}
